import { AutoComplete, Button, DatePicker, message, Popconfirm, Radio,Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { history, Link } from 'umi';
import { DICT_TYPE,getOptions,getStudentSearchOptions, selectStudent } from '@/global/service';
import AddForm from './components/AddForm';
import SendForm from './components/SendForm'
import ExportButton from '@/components/ExportButton';
import ProTable from '@ant-design/pro-table';
import { baseUrl } from '@/utils/httpUrl';

import {
  getReviewList,
  listSendStatusCount,
  listReviewStatusCount,
  getGroupList,
  startReview,
  sendStudent,
  delReview,
  rewrite,
  updateVideo,
  resetVideo
} from './service'
import ProForm from '@ant-design/pro-form';
const { Option } = Select;
const margin5 = {
  margin:'0 5px'
}

// 复盘状态 reviewStatus
// UNDO  待复盘
// DOING 复盘中
// DONE   已完成

const REVIEW_STATUS_UNDO = 'UNDO';
const REVIEW_STATUS_DOING = 'DOING';
const REVIEW_STATUS_DONE = 'DONE';

const REVIEW_MAP = {
  'UNDO' : '待复盘',
  'DOING' : '复盘中',
  'DONE': '已完成'
}
console.log(REVIEW_MAP)
// 发送状态 sendStatus
// UNSEND 未发送
// SENDED  已发送
// UNDO DONE

const SEND_STATUS_UNSEND = 'UNSEND';
const SEND_STATUS_SENDED = 'SENDED';
const SEND_STATUS_UNDO = 'UNDO';
const SEND_STATUS_DONE = 'DONE';

// 发起类型

const STUDENT_APPLY = 'STUDENT_APPLY'
const TEACHER_TRIGGER = 'TEACHER_TRIGGER'

const TableList: React.FC<{}> = (props: any) => {
  const { className } = props
  const { id : courseId } = history.location.query || {};
  const actionRef = useRef<ActionType>();
  const [modalAddVisible, setModalAddVisible] = useState<boolean>(false);
  const [modalEditVisible, setModalEditVisible] = useState<boolean>(false);
  const [modalType, setModalType] = useState<'add' | 'edit' | ''>('');
  const [sendStatus, setSendStatus] = useState<any>(SEND_STATUS_UNSEND);
  const [reviewStatus,setReviewStatus] = useState<any>(REVIEW_STATUS_UNDO)
  const [sendList,setSendList] = useState<any>([])
  const [reviewList,setReviewList] = useState<any>([])
  const [options, setOptions] = useState<any>([]);
  const [classOption,setClassOption] = useState<any>([]);
  const [params,setParams] = useState<any>({})
  const [uid, setUid] = useState<any>();
  const [curId,setCutId] = useState<any>()
  const changeSendStatus = (e) => {
    setSendStatus(e.target.value);
  };
  const changeReviewStatus = (e) => {
    setReviewStatus(e.target.value);
  }
  const onSelectUser = (data: any, option: any) => {
    setUid(option.id);
  };


  const onSearchUser = async (key: string) => {
    try {
      const data = await selectStudent({
        param:key,
        courseId,
      });
      const options = getStudentSearchOptions(key, data);
      setOptions(options);
    } catch (error) {
      message.error('搜索失败');
    }
  };

  const getTabInfo = () => {
    listSendStatusCount({
      courseId,
    }).then(res=>{
      setSendList(res.result)
    })
    listReviewStatusCount({
      courseId,
      sendStatus
    }).then(res=>{
      setReviewList(res.result)
    })
  }
  const onReload = () => {
    if (actionRef.current) {
      getTabInfo()
      actionRef.current.reload();
    }
  };
  const startReviewHandler = async (reviewId: any) => {

    if(window.electron){
      window.electron.ipcRenderer.openElectron({
        reviewId
      })
    } else {
      message.error('web端无法复盘')
    }

  }
  const rewriteHandler = async (reviewId: any) => {
    const res = await rewrite({reviewId})
    if(res.code === 200){
      setReviewStatus(REVIEW_STATUS_UNDO)
      if(sendStatus === SEND_STATUS_SENDED){
        setSendStatus(SEND_STATUS_UNDO)
      }
    } else {
      message.error(res.message)
    }
  }
  const resetVideoHandler = async (reviewId: any) => {
    const res = await resetVideo({reviewId})
    if(res.code === 200){
      setReviewStatus(REVIEW_STATUS_UNDO)
      if(sendStatus === SEND_STATUS_SENDED){
        setSendStatus(SEND_STATUS_UNDO)
      }
    } else {
      message.error(res.message)
    }
  }
  useEffect(() => {
    getTabInfo()
    getGroupList({
      courseId,
    }).then(res=>{
      setClassOption(res.result)
    })
  },[])
  useEffect(()=>{
    onReload()
  },[sendStatus,reviewStatus])
  useEffect(()=>{
    listReviewStatusCount({
      courseId,
      sendStatus
    }).then(res=>{
      setReviewList(res.result)
    })
  },[sendStatus])
  const columns: ProColumns<any>[] = [
    {
      title: '用户昵称/手机号',
      dataIndex: 'key',
      hideInTable: true,
      order: 90,
      formItemProps: { labelCol: { span: 8 } },
      renderFormItem: () => (
        <AutoComplete
          options={options}
          onSelect={onSelectUser}
          onSearch={onSearchUser}
          placeholder="请选择"
          allowClear
          onClear={() => {
            setUid(null);
          }}
        />
      ),
    },

    {
      title: '用户昵称',
      dataIndex: 'nickName',
      hideInSearch: true,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      hideInSearch: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true,
    },
    {
      title: '班级',
      dataIndex: 'groupId',
      hideInTable: true,
      renderFormItem:()=>(
        <Select onChange={e=>{console.log(e)}}>
          {classOption.map((item: any) => (
            <Option key={item.id} value={item.id}>{item.name}</Option>
          ))}
        </Select>
      )
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      hideInSearch: true,
    },
    {
      title: '申请复盘时间',
      dataIndex: 'applyTime',
      hideInSearch: true,
    },
    {
      title: '棋谱ID',
      dataIndex: 'gameId',
    },
    {
      title: '执子',
      dataIndex: 'userColor',
      hideInSearch: true,
    },
    {
      title: '对弈结果',
      dataIndex: 'result',
      hideInSearch: true,
      render:(result,item)=>{
        if(item.gameType !== 'GRADE_GAME'){
          return result
        }
        // 胜利失败取用户在当前对局的胜利或失败情况
        // W/B为该局对弈胜利方执子情况，执白为W，执黑为B
        // 若未中盘胜，则展示为W/B+R
        // 若为超时胜，则展示为W/B+T
        // 若胜X目，则展示为W/B+X
        const [whoPlay, type] = result.split('+');
        const whoPlayMap: any = {
          W: '白',
          B: '黑',
        };
        const typeMap: any = {
          R: '中盘胜',
          T: '超时',
        };
        return `${whoPlayMap[whoPlay]}${typeMap[type] || `胜${type}目`}`;
      }
    },
    {
      title: '用时',
      dataIndex: 'costTime',
      hideInSearch: true,
    },
    {
      title: '手数',
      dataIndex: 'steps',
      hideInSearch: true,
    },
    {
      title: '棋谱类型',
      dataIndex: 'gameType',
      request: getOptions(DICT_TYPE.gameType),
      hideInTable:true
    },
    {
      title: '棋谱类型',
      dataIndex: 'gameTypeStr',
      hideInSearch: true,
    },
    {
      title: '复盘类型',
      dataIndex: 'reviewType',
      request: getOptions(DICT_TYPE.review),
      hideInTable:true
    },
    {
      title: '复盘类型',
      dataIndex: 'reviewTypeStr',
      hideInSearch: true,
    },
    {
      title: '复盘老师',
      dataIndex: 'realTeacherName',
      hideInSearch: true,
    },
    {
      title: '老师复盘时间',
      dataIndex: 'reviewTime',
      hideInSearch: true,
    },
    {
      title: '发送状态',
      dataIndex: 'sendStatusStr',
      hideInSearch: true,
    },
    {
      title: '发送学员时间',
      dataIndex: 'sendTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      hideInSearch: true,
      fixed: 'right',
      align: 'center',
      render:(_: any,item: any)=>([
        (
          item.reviewStatus === REVIEW_STATUS_UNDO &&
          <a key="start" onClick={()=>{startReviewHandler(item.id)}}>
            开始复盘
          </a>
        ),
        (

            item.reviewStatus === REVIEW_STATUS_DOING

          &&
          <Popconfirm
            placement="top"
            title={'是否将当前复盘重置为待复盘状态?'}
            onConfirm={() => {
              resetVideoHandler(item.id)
            }}
            okText="确定"
            cancelText="取消"
          >
           <a key="restart" style={margin5} >重置</a>
          </Popconfirm>
        ),
        (
          item.reviewStatus === REVIEW_STATUS_DONE &&
          <Popconfirm
            placement="top"
            title={'是否将当前复盘重置为待复盘状态?'}
            onConfirm={() => {
              rewriteHandler(item.id)
            }}
            okText="确定"
            cancelText="取消"
          >
          <a key="restart" style={margin5} >重新录制</a>
          </Popconfirm>
        ),
        (
          item.reviewStatus === REVIEW_STATUS_DONE &&
          <a
            key="view"
            target="_blank"
            style={margin5}
            href={`${baseUrl.webview}/game_review_s?reviewId=${item.id}&isTeacher=1`}
            rel="noreferrer"
            >查看复盘
          </a>
        ),
        (
          (
            item.reviewStatus === REVIEW_STATUS_DONE &&
            item.sendStatus === SEND_STATUS_UNSEND
          ) &&
          <Popconfirm
            placement="top"
            title={'是否将当前复盘视频发送给学员？'}
            onConfirm={async () => {
              const res =  await sendStudent({reviewId:item.id})
              if(res.code === 200){
                message.success('发送成功')
                setSendStatus(SEND_STATUS_SENDED)
                onReload()
              } else {
                message.error(res.message)
              }
            }}
            okText="确定"
            cancelText="取消"
          >
           <a key="send" style={margin5}>发至学员</a>
          </Popconfirm>
        ),
        (
          (
            item.reviewStatus === REVIEW_STATUS_DONE &&
            (
              item.sendStatus === SEND_STATUS_SENDED ||
              item.sendStatus === SEND_STATUS_DONE
            ) ) &&
            <a
              key="send-other"
              style={margin5}
              onClick={()=>{
                setModalAddVisible(true)
                setModalType('send')
                setCutId(item.id)
              }}>
                发送给其他学员
            </a>
          ),
        (
          (item.reviewStatus === REVIEW_STATUS_DONE &&
            item.sendStatus === SEND_STATUS_UNDO) &&
            <Popconfirm
              placement="top"
              title={'是否更新当前复盘视频并再次发送给学员？'}
              onConfirm={async () => {
                const res =  await updateVideo({id:item.id})
                  if(res.code === 200){
                    message.success('操作成功')
                    setSendStatus(SEND_STATUS_DONE)
                    onReload()
                  } else {
                    message.error(res.message)
                  }
                }}
                okText="确定"
                cancelText="取消"
             >
              <a key="re-record" style={margin5}>更新复盘视频</a>
            </Popconfirm>
        ),
        (
          (
            item.reviewStatus === REVIEW_STATUS_DONE &&
            item.sendStatus === SEND_STATUS_UNSEND &&
            item.reviewType === TEACHER_TRIGGER
          ) &&
           <Popconfirm
              placement="top"
              title={'是否删除当前复盘？'}
              onConfirm={async () => {
                const res =  await delReview({reviewId:item.id})
                if(res.code === 200){
                  message.success('删除成功')
                  onReload()
                } else {
                  message.error(res.message)
                }
              }}
              okText="确定"
              cancelText="取消"
            >
              <a key="del" style={margin5}>删除</a>
            </Popconfirm>
         )
      ])
    }
  ];

  return (
    <>
      <ProForm.Item label="发送状态">
        <Radio.Group value={sendStatus} onChange={changeSendStatus} style={{ marginBottom: 10 }}>
          {
            sendList.map(item => (
              <Radio.Button key={item.sendStatus} value={item.sendStatus} style={{ marginRight: 10 }}>
                {item.sendStatusDesc}(<span>{item.count}</span>)
              </Radio.Button>
            ))
          }
        </Radio.Group>
      </ProForm.Item>
      <ProForm.Item label="复盘状态">
        <Radio.Group value={reviewStatus} onChange={changeReviewStatus} style={{ marginBottom: 10 }}>
        {
            reviewList.map(item => (
              <Radio.Button key={item.reviewStatus} value={item.reviewStatus} style={{ marginRight: 10 }}>
                {item.reviewStatusDesc}(<span>{item.count}</span>)
              </Radio.Button>
            ))
          }
        </Radio.Group>
      </ProForm.Item>
      <ProTable<any>
        scroll={{ x: 1700 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (cfg: any) => {
          const _cfg = {
            ...cfg,
            reviewStatus,
            courseId,
            sendStatus,
            uid,
            pageNo:cfg.current
           }
          setParams(_cfg)
          const msg = await getReviewList(_cfg);
          return {
            data: msg.result.records,
            success: true,
            total: msg.result.total,
          };
        }}
        search={{
          defaultCollapsed: false,
        }}
        onReset={() => {
          setUid()
        }}
        toolbar={{
          actions: [
            <Button
                type="primary"
                htmlType="submit"
                style={{marginRight:'10px'}}
                onClick={()=>{
                  setModalAddVisible(true)
                  setModalType('add')
                }}
                key="btn1"
                >
              添加三方棋谱
            </Button>,
           <ExportButton
              fileName={`${className} ${REVIEW_MAP[reviewStatus]}`}
              type="reviewList"
              fileType="xls"
              data={params}
              key="btn2"
            />,
          ],
        }}
      />
      <AddForm
        modalAddVisible={modalAddVisible && modalType === 'add'}
        courseId={courseId}
        onCancel={() => {
          setModalAddVisible(false);
        }}
        onReload={onReload}
      />
      <SendForm
        modalAddVisible={modalAddVisible && modalType === 'send'}
        id={curId}
        courseId={courseId}
        onCancel={() => {
          setModalAddVisible(false);
        }}
        onReload={onReload}
      />
    </>
  );
};

export default TableList;
